<template>
    <el-dialog :visible.sync="showAddModal" :append-to-body="true"
               :close-on-click-modal="false" width="40%"
               :close-on-press-escape="false" :show-close="false" class="ele-modal">
        <h4 slot="title">{{modalLabel}}</h4>
        <el-form :model="newForm" class="demo-form-inline" :rules="rules" ref="ruleForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="分类名称" :label-width="formLabelWidth" prop="categoryName">
                        <el-input v-model="newForm.categoryName" auto-complete="off"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="分类图片" :label-width="formLabelWidth" class="ele-upload-item" prop="picUrl">
                        <template v-if="$isEmptyStr(newForm.picUrl)">
                            <el-upload ref="upload" name="upFile"
                                       :class="{'ele-upload':disableUpload}"
                                       :action="getUploadUrl()"
                                       list-type="picture-card"
                                       :limit="1"
                                       :multiple="true"
                                       accept="image/png,image/gif,image/jpeg"
                                       :auto-upload="true"
                                       :before-upload="beforeUpload"
                                       :on-preview="handlePictureCardPreview"
                                       :on-change="handleChange"
                                       :on-remove="handleRemove"
                                       :file-list="fileList">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible" size="tiny" :append-to-body="true">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                            <span style="font-size: 12px;">{{fileName}}</span>
                        </template>
                        <template v-else>
                            <ul class="bill-tips clearfix" v-if="!$isEmptyStr(newForm.picUrl)">
                                <li style="width: 15%;">
                                    <img
                                        style="height: 150px;width: 150px;margin-bottom: 6px;margin-top: 6px;float: left;"
                                        :src="newForm.picUrl">
                                    <el-button type="text" @click="onChangePic" size="small"
                                               style="color: #1ab394;text-decoration: underline">
                                        点击更换图片
                                    </el-button>
                                </li>
                            </ul>
                        </template>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="分类排序" :label-width="formLabelWidth" prop="sort">
                        <el-select v-model="newForm.sort" placeholder="请选择分类排序">
                            <el-option label="1" value="1"></el-option>
                            <el-option label="2" value="2"></el-option>
                            <el-option label="3" value="3"></el-option>
                            <el-option label="4" value="4"></el-option>
                            <el-option label="5" value="5"></el-option>
                            <el-option label="6" value="6"></el-option>
                            <el-option label="7" value="7"></el-option>
                            <el-option label="8" value="8"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

        </el-form>
        <div slot="footer" class="row" style="text-align: center">
            <a class="revision-btn" href="javaScript:void(0)" @click="onSubmit">保 存</a>
            <a class="revision-btn-default" style="margin-left: 5px;" href="javaScript:void(0)" @click="onCancel">取
                消</a>
        </div>
    </el-dialog>
</template>

<script>

    export default {
        name: "addCategoryModal",
        props: {
            showAddModal: {
                type: Boolean,
                default: false
            },
            editId: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                modalLabel: '新增分类',
                newForm: {
                    categoryName: '',
                    sort: '',
                    picUrl: '',
                    categoryId: ''
                },
                formLabelWidth: '100px',
                rules: {
                    categoryName: [
                        {required: true, message: '请输入分类名称', trigger: 'blur'}
                    ],
                    sort: [
                        {required: true, message: '请选择分类排序', trigger: 'change'}
                    ]
                },
                dialogImageUrl: '',
                dialogVisible: false,
                fileList: [],
                uploadFiles: [],
                uploadFile: {},
                uploadUrl: '/sys/oss/upload',
                formData: {},
                uploadedFiles: [],
                disableUpload: false,
                uploadedFileMap: new Map(),
                fileName: '',
            }
        },
        mounted: function () {
        },
        methods: {
            onCancel() {
                //reset upload cfg
                this.$refs.ruleForm.resetFields();
                this.newForm = this.$options.data().newForm;
                this.$nextTick(() => {
                    this.$refs.upload.clearFiles();
                });
                this.initUploadCfg();

                this.$emit('onCancelNewModal');
            },
            onSubmit() {
                if (this.uploadedFileMap === null || this.uploadedFileMap.size === 0) {
                    if (this.$isEmptyStr(this.editId) || this.$isEmptyStr(this.newForm.pic)) {
                        this.$message.warning('请选择图片');
                        return;
                    }
                }
                this.newForm.picUrl = this.uploadedFiles[0];

                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        if (this.$isEmptyStr(this.editId)) {
                            this.submitNewInfo();
                        } else {
                            this.submitEditInfo();
                        }
                    } else {
                        return false;
                    }
                });
            },
            async getInfo(editId) {
                let res = await this.$api.get('/mall/category/info/' + editId, {});
                if (res.code === 0) {
                    this.newForm = res.category;
                } else {
                    this.$message.error(res.msg);
                }
            },
            async submitEditInfo() {
                let res = await this.$api.post('/mall/category/update', this.newForm);
                if (res.code === 0) {
                    //reset upload cfg
                    this.$refs.ruleForm.resetFields();
                    this.newForm = this.$options.data().newForm;
                    this.initUploadCfg();
                    this.$nextTick(() => {
                        this.$refs.upload.clearFiles();
                    });

                    this.$message.success('保存成功');
                    this.$emit('onSubmitNewModal');
                } else {
                    this.$message.error(res.msg);
                }
            },
            async submitNewInfo() {
                let res = await this.$api.post('/mall/category/save', this.newForm);
                if (res.code === 0) {
                    //reset upload cfg
                    this.$refs.ruleForm.resetFields();
                    this.newForm = this.$options.data().newForm;
                    this.initUploadCfg();
                    this.$nextTick(() => {
                        this.$refs.upload.clearFiles();
                    });

                    this.$message.success('保存成功');
                    this.$emit('onSubmitNewModal');
                } else {
                    this.$message.error(res.msg);
                }
            },
            /* ******** File Upload config start ******** */
            initUploadCfg() {
                this.fileName = '';
                this.uploadedFiles.pop();
                this.uploadedFileMap.clear();
                this.disableUpload = false;
            },
            getUploadUrl() {
                return '/api/sys/oss/upload';
            },
            async submitUpload() {
                let res = await this.$api.post(this.uploadUrl, this.formData);
                if (res.code === 0) {
                    this.uploadedFiles.push(res.url);
                } else {
                    this.$message.error(res.msg);
                }
            },
            beforeUpload(file) {
                this.formData = new FormData();
                this.formData.append('file', file);
                this.submitUpload();

            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleChange(file, fileList) {
                this.fileName = file.name;
                this.uploadedFileMap.set(file.uid, file.url);
                if (fileList.length === 1) {
                    this.disableUpload = true;
                }
            },
            handleRemove(file, fileList) {
                this.fileName = '';
                this.uploadedFileMap.delete(file.uid);
                this.uploadedFiles.pop();

                if (fileList.length < 1) {
                    this.disableUpload = false;
                }
            },
            onChangePic() {
                this.newForm.picUrl = '';
                this.initUploadCfg();
            },
            /* ******** File Upload config end ******** */
        }
    }
</script>

<style scoped>
    .ele-modal /deep/ .el-form-item__label {
        font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 12px;
        color: #676a6c;
    }

    .ele-modal /deep/ .el-radio__label {
        font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 12px;
        color: #676a6c;
        font-weight: normal;
    }

    .ele-modal /deep/ .el-select {
        display: inline;
    }

    /deep/ .el-upload__input {
        display: none;
    }

    /deep/ .el-dialog__wrapper {
        z-index: 3000;
    }

    .ele-modal /deep/ .el-dialog__header {
        border-bottom: 1px solid #e5e5e5;
        padding: 5px 0 2px 15px !important;
    }

    .ele-modal /deep/ .el-dialog__body {
        padding: 20px;
    }

    .ele-modal /deep/ .el-dialog__footer {
        border-top: 1px solid #e5e5e5;
        padding: 15px;
    }

    /* ******** File Upload config start ******** */
    .ele-upload /deep/ .el-upload--picture-card {
        display: none;
    }

    .ele-upload-item /deep/ .el-form-item__content {
        line-height: 0;
    }

    /* ******** File Upload config end ******** */
</style>
